package com.smarkparking.controller;

import com.github.wxpay.sdk.PayUtil;
import com.smarkparking.pojo.Order;
import com.smarkparking.pojo.PayResultDTO;
import com.smarkparking.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @author 刘涛
 * @create 2021/11/23 8:26
 */
@CrossOrigin
@RestController
public class PayController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private PayUtil payUtil;

    @RequestMapping("/pay")
    public String getPayUrl(@RequestParam("id") Long orderId) throws Exception {
        // 1.根据id查询订单
        Order orderById = orderService.findOrderById(orderId);
        // 2.判断订单状态，是否已支付
        // 2.1.如果已经支付，则说明是重复调用，报错即可
        if (orderById.getOrderState() == 1) {
            throw new Exception("状态异常");
        }
        // 2.2.如果是未支付，则调用payUtil.unifiedOrder()
        return payUtil.unifiedOrder("停车支付", Long.valueOf(orderId), 1L);
    }

    /**
     * 处理微信的异步通知
     *
     * @param data 通知内容
     * @return 处理结果
     */
    @PostMapping(value = "/pay/notify", produces = MediaType.APPLICATION_XML_VALUE)
    public ResponseEntity<PayResultDTO> handleWxNotify(@RequestBody Map<String, String> data) {
        orderService.handleNotify(data);
        return ResponseEntity.ok(new PayResultDTO());
    }

    @RequestMapping("/payState")
    public boolean payState(Long id) {
        return orderService.payState(id);
    }
}
